package com.leyou.page.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.page.service.IPageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @author xiuer
 * @description 监听商品微服务消息
 * @create 2019/7/5 20:09
 */
@Component
@Slf4j
public class ListenerItemMQ {

    private static final String htmlPath = "E:\\javaTool\\nginx-1.12.2\\html\\item\\";
    @Autowired
    private IPageService pageService;

    //监听MQ 商品上架
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.Queue.PAGE_ITEM_UP, durable = "true"),
            exchange = @Exchange(
                    value = MQConstants.Exchange.ITEM_EXCHANGE_NAME,
                    type = ExchangeTypes.TOPIC
            ),
            key = MQConstants.RoutingKey.ITEM_UP_KEY))
    public void listenerMQUp(Long id) {
        if (id != null) {
            //新增或者修改
            pageService.creatItemHtml(id);
        }
    }

    //监听MQ 商品下架 删除静态页面
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.Queue.PAGE_ITEM_DOWN, durable = "true"),
            exchange = @Exchange(
                    value = MQConstants.Exchange.ITEM_EXCHANGE_NAME,
                    type = ExchangeTypes.TOPIC
            ),
            key = MQConstants.RoutingKey.ITEM_DOWN_KEY))
    public void listenerMQdown(Long id) {
        if (id != null) {
            File file = new File(htmlPath + id + ".html");
            if (file.exists()) {
                if (!file.delete()) {
                    log.error("【静态页面微服务】静态页面删除失败商品id {}", id);
                    throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
                }
            }

        }
    }
}
